import axios from "axios";
import {
  AxiosRequestConfig,
  AxiosResponse,
  Method
} from "axios";
import {
  clearLocalStorage,
  hasOwnProperty
} from "@/utils/utils";
import {
  message
} from "ant-design-vue";
import {
  BASE_URL
} from "@/utils/utils.ts";
import router from "@/router";
interface PendingType {
  url: string;
  method ? : Method;
  params: any;
  data: any;
  cancel: any;
}

const pending: Array < PendingType > = [];

const removePending = (config: AxiosRequestConfig) => {
  for (const key in pending) {
    if (hasOwnProperty(pending, key)) {
      const item: number = +key;
      const list: PendingType = pending[key];
      if (
        list.url === config.url &&
        list.method === config.method &&
        JSON.stringify(list.params) === JSON.stringify(config.params) &&
        JSON.stringify(list.data) === JSON.stringify(config.data)
      ) {
        list.cancel("操作太频繁，请稍后再试");
        pending.splice(item, 1);
      }
    }
  }
};

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 8000000,
});

instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token: string = localStorage.getItem("token") as string;
    removePending(config);
    if (token) {
      config.headers["token"] = token;
    }
    return config;
  },

  (error: any) => {
    return Promise.reject(error);
  }
);
instance.interceptors.response.use(
  async (response: AxiosResponse < any > ) => {

      removePending(response.config);
      const {
        data
      } = response;
      if (data.code === 10003) {
        const routeName = router.currentRoute.name
        if (routeName !== "Home" && routeName !== "DetailPage") {
          message.error("登陆超时");
        }
        await clearLocalStorage();
        setTimeout(() => {
          if (routeName === "DetailPage") {
          //  window.location.reload();
           return
          }
          router.push("/");
          // window.location.reload();
        }, 1000);
        
        return response.data;
      }
      return response.data;
    },
    /**
     * 这边需要将window.location.reload()改成this.$router
     * @param error
     */
    (error) => { 
      // const confirm = window.confirm("网络连接失败");

      // if (confirm) {
      //   clearLocalStorage();
      //   window.location.reload();
      // }
      // message.error("网络连接失败,请刷新重试");
      return Promise.reject(error);
    }
);

export default instance;